import 'package:bruno/bruno.dart';
import 'package:common/common.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebArguments {
  final String title;
  final String initialUrl;
  final bool showAppbar;
  final List<Widget> actions;
  WebArguments({
    required this.initialUrl,
    this.title = '',
    this.showAppbar = true,
    this.actions = const [],
  });
}

/// webview 封装
class WebViewPage extends StatefulWidget {
  final WebArguments arguments;

  const WebViewPage({Key? key, required this.arguments}) : super(key: key);

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  WebViewController? webViewController;
  final _key = UniqueKey();
  String title = '';
  bool _showAppbar = true;
  int _stackToView = 1;
  String? _initialUrl;
  double _webViewHeight = 200;

  late WebViewController controller;

  @override
  void initState() {
    super.initState();

    title = widget.arguments.title;
    _showAppbar = widget.arguments.showAppbar;
    _initialUrl = widget.arguments.initialUrl;

    // Enable virtual display.
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // Update loading bar.
          },
          onPageStarted: (String url) {},
          onPageFinished: (String url) {},
          onHttpError: (HttpResponseError error) {},
          onWebResourceError: (WebResourceError error) {},
          onNavigationRequest: (NavigationRequest request) {
            return NavigationDecision.navigate;
          },
        ),
      )
      ..loadRequest(Uri.parse(_initialUrl!));
  }

  @override
  void dispose() async {
    // 销毁 WebView 实例
    // webViewController?.loadUrl('about:blank');
    // webViewController?.clearCache();

    super.dispose();
  }

  @override
  void didUpdateWidget(covariant WebViewPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.arguments.initialUrl != oldWidget.arguments.initialUrl) {
      super.didUpdateWidget(oldWidget);
    }
  }

  // // 注册js回调
  // _invokeJavascriptChannel(BuildContext context) {
  //   return [
  //     JavascriptChannel(
  //       name: 'Invoke',
  //       onMessageReceived: (JavascriptMessage message) {
  //         // var webHeight = double.parse(message.message);
  //         // setState(() {
  //         //   print('打印webHeight:$_webViewHeight');
  //         //   _webViewHeight = webHeight;
  //         // });
  //       },
  //     ),
  //     JavascriptChannel(
  //       name: 'Invoke1',
  //       onMessageReceived: (JavascriptMessage message) {
  //         // var devicePixelRatio = double.parse(message.message);
  //         // setState(() {
  //         // _webViewHeight = devicePixelRatio;
  //         // });
  //       },
  //     ),
  //     JavascriptChannel(
  //       name: "integral",
  //       onMessageReceived: (JavascriptMessage message) {
  //         // print("交互");
  //         // print("参数： ${message.message}");
  //         // Map res = changeStringToJsonMap(message.message);
  //         // print(res["operation"]);
  //         // _controller?.evaluateJavascript("getAddressBook('sdad')");
  //       },
  //     ),
  //     JavascriptChannel(
  //       name: "MessageDeal",
  //       onMessageReceived: (JavascriptMessage message) async {
  //         // print("交互");
  //         // print("参数： ${message.message}");
  //         // print(webViewController);
  //         // webViewController
  //         //     ?.runJavascriptReturningResult("showMessage('我（Flutter）收到了你的消息)");
  //         // _controller?.evaluateJavascript("document.title");
  //       },
  //     ),
  //     JavascriptChannel(
  //       name: "callWithDict",
  //       onMessageReceived: (JavascriptMessage message) {
  //         // print("交互");
  //         // print("参数： ${message.message}");
  //       },
  //     ),
  //   ];
  // }

  // 获取页面高度
  _getWebViewHeight() async {
    // 方式一：
    // await webViewController?.runJavascriptReturningResult('''
    //     try {
    //       // Invoke.postMessage([document.body.clientHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight]);
    //       let scrollHeight = document.documentElement.scrollHeight;
    //       if (scrollHeight) {
    //         Invoke.postMessage(scrollHeight);
    //       }
    //     } catch {}
    //     ''');
    // 方式二：
    // var originalHeight = await webViewController!.runJavascriptReturningResult("document.body.offsetHeight;");
    // _webViewHeight = double.parse(originalHeight);
    // setState(() {
    //   _webViewHeight = _webViewHeight <= 0 ? 300 : _webViewHeight;
    // });
    // print('网页高度-----' + _webViewHeight.toString());
  }

  // 返回与后退的处理
  Future<bool> _onWillPop() async {
    if (webViewController == null) {
      logs("WebView都没有加载成功，直接返回退出即可");
      //WebView都没有加载成功，可以直接退出
      Navigator.of(context).pop();
      return false;
    } else {
      //如果点击了内部链接之后，可以返回，则直接返回
      if (await webViewController!.canGoBack()) {
        logs("点击内部链接，可以后台，调用后退");
        await webViewController!.goBack();
        return false; // 防止退出页面
      } else {
        logs("点击内部链接，无法后退，直接返回");
        if (mounted) {
          Navigator.of(context).pop(); // 不能后退则退出当前页面
        }
        return true;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: _showAppbar
            ? BrnAppBar(
                title: title,
                backgroundColor: Colors.white,
                actions: widget.arguments.actions,
                backLeadCallback: _onWillPop)
            : null,
        body: SafeArea(
          bottom: false,
          top: false,
          child: IndexedStack(
            index: _stackToView,
            children: [
              Column(
                children: [
                  Expanded(
                    child: PopScope(
                      canPop: false, // 允许返回
                      onPopInvoked: (bool didPop) async {
                        if (didPop) {
                          return;
                        }
                        _onWillPop();
                      },
                      // onWillPop: _onWillPop,
                      child: WebViewWidget(controller: controller),
                    ),
                  )
                ],
              ),
              Container(
                color: Colors.white,
                child: const Center(
                  child: CircularProgressIndicator(
                    strokeWidth: 3,
                    valueColor: AlwaysStoppedAnimation(Color(0xFF22F2EB)),
                  ),
                ),
              ),
            ],
          ),
        ));
  }
}
